package com.afs.electronicforensics.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;

import com.afs.electronicforensics.activity.R;
import com.afs.electronicforensics.activity.ResetPasswordActivity;
import com.afs.electronicforensics.activity.ShowActivity;
import com.afs.electronicforensics.entity.Result;
import com.afs.electronicforensics.entity.UserPath;
import com.afs.electronicforensics.utils.CheckPhone;
import com.afs.electronicforensics.utils.Constants;
import com.afs.electronicforensics.utils.SendCode;
import com.afs.electronicforensics.monitor.LoginMonitorEditText;
import com.afs.electronicforensics.utils.TimeCount;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;

public class SignInFragment extends Fragment {
    EditText username, phone, password, code;
    ConstraintLayout cbf_linearLayout,code_linearLayout;
    CheckBox checkBox;
    TextView forgetPwd,sendCode,changeLogin,phoneLogin,pwdLogin;
    //设置登陆请求网址
    String loginUrl = null;

    //验证码倒计时
    private TimeCount time;

    //记住密码
    SharedPreferences sp = null;

    //手机号设置
    String tel = "";
    //验证码设置
    String word = "";
    //验证码设置
    char[] checkCode ={'0','1','2','3','4','5','6','7','8','9'};

    float vp = 0;
    boolean changeFlag = true;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup root =(ViewGroup) inflater.inflate(R.layout.signin_fragment,container,false);

        sp = this.getActivity().getSharedPreferences("userInfo", Context.MODE_PRIVATE);

        username = root.findViewById(R.id.username);
        phone = root.findViewById(R.id.phone);

        code_linearLayout = root.findViewById(R.id.code_linearLayout);
        code=root.findViewById(R.id.code);
        sendCode = root.findViewById(R.id.send_code);
        time = new TimeCount(60000, 1000,sendCode); ;

        password =root.findViewById(R.id.password);
        cbf_linearLayout = root.findViewById(R.id.cbf_linearLayout);
        checkBox = root.findViewById(R.id.remember);
        forgetPwd =root.findViewById(R.id.forget_pwd);
        phoneLogin=root.findViewById(R.id.phone_login);
        pwdLogin=root.findViewById(R.id.pwd_login);
        changeLogin =root.findViewById(R.id.change_login);

        //edittext动态监测
        new LoginMonitorEditText().SetMonitorEditText(phoneLogin,phone,code);
        new LoginMonitorEditText().SetMonitorEditText(pwdLogin,username,password);
        new LoginMonitorEditText().SetMonitorEditText(sendCode,phone);

        //展示手机登录
        phoneAnim();

        //获取记住的账号密码
        sp = getActivity().getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        if (sp.getBoolean("checkboxBoolean", false)){
            username.setText(sp.getString("name", null));
            password.setText(sp.getString("pwd", null));
            checkBox.setChecked(true);
        }

        //忘记密码跳转
        forgetPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent=new Intent(getActivity(), ResetPasswordActivity.class);
                startActivity(intent);
                //getActivity().finish();

            }
        });


        sendCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String pNo = phone.getText().toString().trim();
                if(pNo.length()==0||pNo.equals("")){
                    Toast.makeText(getActivity(),"手机号码输入为空！",Toast.LENGTH_SHORT).show();
                }else if(!CheckPhone.isMobileNO(pNo)){
                    Toast.makeText(getActivity(),"手机号码格式有误！",Toast.LENGTH_SHORT).show();
                    phone.setText(null);
                }else{
                    String path = Constants.URL_ROOT+"user/findByPhone?phone="+pNo;//判断手机号码是否存在
                    new Verification().execute(path);
                }
            }
        });



        pwdLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = username.getText().toString().trim();
                String pwd = password.getText().toString().trim();
                loginUrl = Constants.URL_ROOT+"user/login"+"?name=" + name +
                        "&password=" + pwd;
                new doLogin().execute(loginUrl);
            }
        });

        phoneLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String getCode = code.getText().toString().trim();
                if(getCode.equals(word)&&!word.equals("")){
                    Toast.makeText(getActivity(), "验证成功！", Toast.LENGTH_SHORT).show();
                    //跳转页面
                    String phoneLoginUrl = Constants.URL_ROOT+"user/findByPhoneAndLogin?phone="+tel;
                    new doPhoneLogin().execute(phoneLoginUrl);
                }else if(word.equals("")){
                    Toast.makeText(getActivity(), "未获取验证码！", Toast.LENGTH_SHORT).show();
                    code.setText(null);
                } else{
                    Toast.makeText(getActivity(), "验证码输入有误!", Toast.LENGTH_SHORT).show();
                    code.setText(null);
                }
            }
        });


        //切换登录模式
        changeLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(changeFlag){
                    pwdAnim();
                    changeFlag = false;
                }else {
                    phoneAnim();
                    changeFlag = true;
                }
            }
        });

        return root;
    }

    //发送验证码
    private class Verification extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] params) {

            String path = params[0].toString();

            try {
                //以get方式提交整个路径
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");//这个应该都知道是干嘛的，默认是GET
                conn.setConnectTimeout(5000);

                if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String str = br.readLine();
                    return str;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            String info = o.toString().trim();
            try {
                JSONObject js = new JSONObject(info);
                String result = js.getString("code").trim();
                if("0".equals(result)){
                    Toast.makeText(getActivity(), "该手机号码不存在，请先注册！", Toast.LENGTH_SHORT).show();
                    phone.setText(null);
                }else if("1".equals(result)){
                    time.start();
                    tel = phone.getText().toString().trim();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            for(int i=0;i<4;i++){
                                word+=checkCode[(int)(checkCode.length*Math.random())];
                            }
                            SendCode sc = new SendCode();
                            String json = sc.bowlingJson(word,tel);
                            try{
                                sc.post("https://open.ucpaas.com/ol/sms/sendsms",json);
                                Looper.prepare();
                                Toast.makeText(getActivity(), "验证码已发送", Toast.LENGTH_SHORT).show();
                                Looper.loop();

                            }catch(IOException e) {
                                Looper.prepare();
                                Toast.makeText(getActivity(), "验证码发送失败", Toast.LENGTH_SHORT).show();
                                Looper.loop();
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }

    //判断登录
    private class doLogin extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] params) {

            String path = params[0].toString();

            try {
                //以get方式提交整个路径
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");//这个应该都知道是干嘛的，默认是GET
                conn.setConnectTimeout(5000);
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                conn.setRequestProperty("Content-Type","application/json;charset=utf-8");
                conn.connect();

                if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String str = br.readLine();
                    return str;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            String info = o.toString().trim();
            JSONObject jo = null;
            try {
                jo = new JSONObject(info);
                if(jo != null){
                    if(jo.getString("code").equals("0")){
                        Toast.makeText(getActivity(), "账号或密码输入错误！", Toast.LENGTH_SHORT).show();
                        username.setText(null);
                        password.setText(null);
                    }else{
                        String data = jo.getString("data");
                        JSONObject jsonData = new JSONObject(data);
                        Constants.USER_ROOT.setUid(jsonData.getString("id"));
                        Constants.USER_ROOT.setUsername(jsonData.getString("name"));
                        Constants.USER_ROOT.setPassword(jsonData.getString("password"));
                        Constants.USER_ROOT.setPhone(jsonData.getString("phone"));
                        if(jsonData.getString("photo").trim() != null && !("").equals(jsonData.getString("photo"))){
                            Constants.USER_ROOT.setUserAvatar(jsonData.getString("photo"));
                        }else{
                            Constants.USER_ROOT.setUserAvatar(null);
                        }
                        System.out.println(jsonData.getString("name"));
                        //设置路径
                        Constants.USER_PATH.setUserPath(jsonData.getString("id"));

                        Toast.makeText(getActivity(), "登录成功！", Toast.LENGTH_SHORT).show();
                        SharedPreferences.Editor editor = sp.edit();
                        if(checkBox.isChecked()==true){
                            editor.putString("name", username.getText().toString().trim());
                            editor.putString("pwd", password.getText().toString().trim());
                            editor.putBoolean("checkboxBoolean", true);
                        }else{
                            editor.putString("name",null);
                            editor.putString("pwd",null);
                            editor.putBoolean("checkboxBoolean", false);
                        }
                        editor.putString("ename", username.getText().toString().trim());
                        editor.putString("epwd", password.getText().toString().trim());
                        editor.putBoolean("autoLogin", true);
                        editor.commit();

                        //跳转页面
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), ShowActivity.class);
                        startActivity(intent);
                        getActivity().finish();
                    }
                }else {
                    Toast.makeText(getActivity(), "未知错误！", Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    //判断手机号登录
    private class doPhoneLogin extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] params) {

            String path = params[0].toString();

            try {
                //以get方式提交整个路径
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");//这个应该都知道是干嘛的，默认是GET
                conn.setConnectTimeout(5000);

                if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String str = br.readLine();
                    return str;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            try {
                String info = o.toString().trim();
                JSONObject jo = new JSONObject(info);
                if (jo.getString("code").equals("1")) {
                    String data = jo.getString("data");
                    JSONObject jsonData = new JSONObject(data);

                    Constants.USER_ROOT.setUid(jsonData.getString("id"));
                    Constants.USER_ROOT.setUsername(jsonData.getString("name"));
                    Constants.USER_ROOT.setPassword(jsonData.getString("password"));
                    Constants.USER_ROOT.setPhone(jsonData.getString("phone"));
                    if (jsonData.getString("photo").trim() != null && !("").equals(jsonData.getString("photo"))) {
                        Constants.USER_ROOT.setUserAvatar(jsonData.getString("photo"));
                    } else {
                        Constants.USER_ROOT.setUserAvatar(null);
                    }

                    System.out.println(jsonData.getString("id"));
                    //设置路径
                    Constants.USER_PATH.setUserPath(jsonData.getString("id"));

                    Toast.makeText(getActivity(), "登录成功！", Toast.LENGTH_SHORT).show();
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("ename", jsonData.getString("name"));
                    editor.putString("epwd", Constants.USER_ROOT.getPassword());
                    editor.putBoolean("autoLogin", true);
                    editor.commit();

                    //跳转页面
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), ShowActivity.class);
                    startActivity(intent);
                    getActivity().finish();
                }else {
                    Toast.makeText(getActivity(), "账号或密码输入错误！", Toast.LENGTH_SHORT).show();
                    username.setText(null);
                    password.setText(null);
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }

    private void pwdAnim(){
        username.setVisibility(View.VISIBLE);
        phone.setVisibility(View.GONE);
        password.setVisibility(View.VISIBLE);
        code_linearLayout.setVisibility(View.GONE);
        cbf_linearLayout.setVisibility(View.VISIBLE);
        phoneLogin.setVisibility(View.GONE);
        pwdLogin.setVisibility(View.VISIBLE);
        changeLogin.setVisibility(View.VISIBLE);

        changeLogin.setVisibility(View.VISIBLE);
        changeLogin.setText("短信验证登录");

        username.setTranslationY(800);
        username.setAlpha(vp);
        username.animate().translationY(0).alpha(1).setDuration(1000).setStartDelay(300).start();

        password.setTranslationY(800);
        password.setAlpha(vp);
        password.animate().translationY(0).alpha(1).setDuration(1000).setStartDelay(500).start();

        cbf_linearLayout.setTranslationY(800);
        cbf_linearLayout.setAlpha(vp);
        cbf_linearLayout.animate().translationY(0).alpha(1).setDuration(1000).setStartDelay(700).start();

        pwdLogin.setTranslationY(800);
        pwdLogin.setAlpha(vp);
        pwdLogin.animate().translationY(0).alpha(1).setDuration(1000).setStartDelay(900).start();

        changeLogin.setTranslationY(800);
        changeLogin.setAlpha(vp);
        changeLogin.animate().translationY(0).alpha(1).setDuration(1000).setStartDelay(1100).start();

    }

    private void phoneAnim(){
        username.setVisibility(View.GONE);
        phone.setVisibility(View.VISIBLE);

        password.setVisibility(View.GONE);
        cbf_linearLayout.setVisibility(View.GONE);

        code_linearLayout.setVisibility(View.VISIBLE);
        pwdLogin.setVisibility(View.GONE);
        phoneLogin.setVisibility(View.VISIBLE);
        changeLogin.setVisibility(View.VISIBLE);
        changeLogin.setText("账号密码登录");

        phone.setTranslationY(800);
        phone.setAlpha(vp);
        phone.animate().translationY(0).alpha(1).setDuration(1000).setStartDelay(300).start();

        code_linearLayout.setTranslationY(800);
        code_linearLayout.setAlpha(vp);
        code_linearLayout.animate().translationY(0).alpha(1).setDuration(1000).setStartDelay(500).start();

        phoneLogin.setTranslationY(800);
        phoneLogin.setAlpha(vp);
        phoneLogin.animate().translationY(0).alpha(1).setDuration(1000).setStartDelay(700).start();

        changeLogin.setTranslationY(800);
        changeLogin.setAlpha(vp);
        changeLogin.animate().translationY(0).alpha(1).setDuration(1000).setStartDelay(900).start();
    }

}
